<?php

namespace app\teacher\controller\learn;

use app\common\controller\Frontend;
use app\common\enums\LatroProficiencyEnum;
use app\common\enums\LearnMeansEnum;
use app\common\model\banxi\course\Lexicon;
use app\common\model\banxi\word\WordDictionary;
use app\common\model\banxi\learn\LearnLatro as LearnLatroModel;
/*
 * 学练一体
 * */
class LearnLatro extends Frontend
{

    protected array $noNeedLogin = [''];

    protected array $noNeedPermission = ['*'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 分页-课程单词
     * @param int $tab tab 0 开始
     * @param int $courseId 课程id
     * @param int $studentId 学员，如果存在就代表着教学
     * @return array
     */
    public function listCourseLexicon($tab, $courseId, $studentId = null)
    {
        $limit = $this->request->get('limit', 20);
        $index = $this->request->get('index', 1);
        $tab = $this->request->get('tab');
        $courseId = $this->request->get('courseId');
        $studentId = $this->request->get('studentId');
        // 获取当前用户ID
        $user = $this->auth->getUserInfo();
        $trainerId = $user['id'];

        $LexiconModel = new Lexicon();
        // 判断是教学场景还是自主学习场景
        $learnMeans = $studentId ? LearnMeansEnum::E1 : LearnMeansEnum::E2; // E1表示教学，E2表示自主学习

        // 构建查询
        $query = $LexiconModel
            ->alias('l');
        $joinCondition = "ll.word = l.word AND ll.courseId = l.courseId";
        if ($studentId) {
            $joinCondition .= " AND ll.studentId = {$studentId}";
        }
        if ($trainerId) {
            $joinCondition .= " AND ll.trainerId = {$trainerId}";
        }
        $joinCondition .= " AND ll.learnMeans = '{$learnMeans}'";

        $query->leftJoin('banxi_learn_latro ll', $joinCondition)
            ->field('l.*, ll.proficiency')
            ->where('l.courseId', $courseId);

        // 根据tab值筛选不同熟练度的单词
        switch ($tab) {
            case 1:
                $query->where('ll.proficiency', LatroProficiencyEnum::E1);
                break;
            case 2:
                $query->where('ll.proficiency', LatroProficiencyEnum::E2);
                break;
            case 3:
                $query->where('ll.proficiency', LatroProficiencyEnum::E3);
                break;
        }

        // 按ID升序排列
        $query->order('l.id', 'asc');

        // 分页查询
        $list = $query->paginate([
            'list_rows' => $limit,
            'page' => $index
        ]);

        // 返回结果
        $this->ok('操作成功', result_row($list));
    }

    /**
     * 查询-单词详情
     *
     * @param Request $request
     * @return Json
     */
    public function getWordDetail()
    {
        $courseId = $this->request->get('courseId', 0);
        $id = $this->request->get('id', 0);
        $proficiency = $this->request->get('proficiency', 0);
        $studentId = $this->request->get('studentId');
        $next = $this->request->get('next', false);
        $studentId = $studentId ? $studentId : null;
        // 获取当前用户ID（教师ID）
        $user = $this->auth->getUserInfo();
        $trainerId = $user['id'];
        // 判断学习方式
        $learnMeans = $studentId ? LearnMeansEnum::E1 : LearnMeansEnum::E2; // E1表示教学，E2表示自主学习

        $LexiconModel = new Lexicon();
        // 获取词汇信息
        if ($next=='true') {
            // 获取下一个单词
            $query = $LexiconModel->where('courseId', $courseId)
                ->where('id', '>', $id)
                ->order('id', 'asc')
                ->limit(1);

            // 如果指定了熟练度，则进行关联查询
            if ($proficiency) {
                $joinCondition = "ll.word = l.word AND ll.courseId = l.courseId";
                if ($studentId) {
                    $joinCondition .= " AND ll.studentId = {$studentId}";
                }
                if ($trainerId) {
                    $joinCondition .= " AND ll.trainerId = {$trainerId}";
                }
                $joinCondition .= " AND ll.learnMeans = '{$learnMeans}'";

                $query->leftJoin('banxi_learn_latro ll', $joinCondition)
                    ->field('l.*, ll.proficiency')
                    ->where('l.courseId', $courseId);
            }

            $lexicon = $query->find();

        } else {
            $lexicon = $LexiconModel->find($id);
        }

        // 检查单词是否存在
        if (!$lexicon) {
            $this->fail('单词不存在');
        }
        // 获取单词字典信息
        $WordDictionaryModel = new WordDictionary();
        $wordDictionary = $WordDictionaryModel->where('word', $lexicon['word'])->find();
        if (!$wordDictionary) {
            $this->fail('单词不存在');
        }

        // 构建返回数据
        $latro = $wordDictionary;
        $latro['word'] = $lexicon['word'];
        $latro['wordId'] = $lexicon['id'];
        $latro['wordCount'] = $LexiconModel->where('courseId', $courseId)->count();

        // 获取熟练度信息
        $LearnLatroModel = new LearnLatroModel();
        $learnLatro = $LearnLatroModel->where('trainerId', $trainerId)
            ->where('studentId', $studentId)
            ->where('learnMeans', $learnMeans)
            ->where('courseId', $courseId)
            ->where('word', $lexicon['word'])
            ->find();

        $latro['proficiency'] = $learnLatro ? $learnLatro['proficiency'] : null;

        // 获取选项（用于测试）

        $options = $WordDictionaryModel->where('translation', 'not null')
            ->limit(2)
            ->orderRaw('RAND()')
            ->column('translation');

        $options[] = $latro['translation'];
        shuffle($options);
        $latro['options'] = $options;

        $latro['phoneticSplit'] = json_decode($latro['phoneticSplit'],true);
        $latro['metaConsonant'] = json_decode($latro['metaConsonant'],true);
        $latro['metaVowel'] = json_decode($latro['metaVowel'],true);
        $latro['exampleSentence'] = json_decode($latro['exampleSentence'],true);

        // 如果没有熟练度信息，则默认设置为E2并记录
        if ($latro['proficiency'] == null) {
            $latro['proficiency'] = LatroProficiencyEnum::E2;

            // 异步记录标记单词（这里简化处理）
            $LearnLatroModel->markProficiency($trainerId, $studentId, $learnMeans, $courseId, $lexicon['word'], LatroProficiencyEnum::E2);
        }

        $this->ok('操作成功', $latro);
    }

    /*
     * 标记单词
     * */
    public function markWord()
    {
        $courseId = $this->request->post('courseId', 0);
        $word = $this->request->post('word', '');
        $proficiency = $this->request->post('proficiency', 0);
        $studentId = $this->request->post('studentId');

        if (!$word){
            $this->fail('单词不能为空');
        }
        $studentId = $studentId ? $studentId : null;
        // 获取当前用户ID（教师ID）
        $user = $this->auth->getUserInfo();
        $trainerId = $user['id'];
        // 判断学习方式
        $learnMeans = $studentId ? LearnMeansEnum::E1 : LearnMeansEnum::E2; // E1表示教学，E2表示自主学习
        $LearnLatroModel = new LearnLatroModel();
        $LearnLatroModel->markProficiency($trainerId, $studentId, $learnMeans, $courseId, $word, $proficiency);

        $this->ok('操作成功');
    }
}